package com.yt.base.controller.base;

import com.yt.base.controller.core.BaseController;
import com.yt.base.util.UploadImageUtils;
import com.yt.core.MsgBean;
import com.yt.util.YitianConfig;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping("/base/image")
public class ImageUploadController extends BaseController {
    @RequestMapping("/upload")
    @ResponseBody
    public Object upload(HttpServletRequest request, @RequestParam(value = "file", required = false) MultipartFile file,
                         @RequestParam(value = "imgFile", required = false) MultipartFile imgFile) {
        MsgBean msg = new MsgBean();
        MultipartFile uploadFile = null;
        if(file != null){
            uploadFile = file;
        }else if(imgFile != null){
            uploadFile = imgFile;
        }

        String fileName = System.currentTimeMillis() + "." + uploadFile.getOriginalFilename().split("\\.")[1];
        try {
            String uri = UploadImageUtils.uploadImage(uploadFile, "product");
            msg.put("uri", uri);
            msg.put("url", YitianConfig.IMAGE_ACCESS_URL + "/" + uri);
            msg.put("error", 0);
        }catch (Exception ex){
            msg.failure("上传失败");
            msg.put("error", 1);
            ex.printStackTrace();
        }finally {
        }
        return msg.returnMsg();
    }
}
